const fs=require("fs");
const path=require("path")
const readFile=(path)=>{
    return new Promise((resolve)=>{
        fs.readFile(path,(err,data)=>{
            if (err){
                throw err
            }
            resolve(data.toString());
        })
    })
}
module.exports=function ({temPath,name,version}){
    let context={};
    let packageJson={};
    let readFileObj={

    };
    return {
        name: 'mk-packageJson', // 这个名字将会出现在在警告和报错中
        buildStart:async function (){
          console.log("mk-packageJson:生成packageJson文件!")
          const contextStr=await readFile(temPath);
          const packageJsonStr=await readFile(path.resolve("./package.json"));
          context=JSON.parse(contextStr);
          packageJson=JSON.parse(packageJsonStr);
          let newVersion=version;
          const pgkVersion=context.version;
          if (!newVersion&&!pgkVersion){
              newVersion="0.0.1"
          }else if (pgkVersion){
              const numArray=pgkVersion.split(".");
              const len=numArray.length;
              let lastVersion=-1;
              for (let i=len-1;i>=0;i--){
                  const item=numArray[i];
                  const itemNum=Number.parseInt(item);
                  let newNum=itemNum;
                  if (!Number.isNaN(itemNum)){
                        if (lastVersion===-1||lastVersion>=10){
                            newNum=newNum+1;
                        }
                        lastVersion=newNum;
                        if (newNum>=10){
                            newNum="0";
                        }
                      numArray[i]=item.replace(itemNum,newNum);
                  }
              }
              newVersion=numArray.join(".");
          }
          context.version=newVersion;
          fs.writeFileSync(temPath,JSON.stringify(context,"","\t"))
        },
        renderChunk:async (code,{fileName,imports})=>{
            if (!readFileObj[fileName]){
                 if (imports.length>0){
                     imports.forEach((item)=>{
                         const relName=item.trim().replace(/"|'|;/g,"");
                         const dependencies=packageJson.dependencies[relName];
                         if (dependencies){
                              context.dependencies[relName]=dependencies;
                              return;
                         }
                         const devDependencies=packageJson.devDependencies[relName];
                         if (devDependencies){
                             context.devDependencies[relName]=devDependencies;
                             return;
                         }
                     })
                 }
                 readFileObj[fileName]=fileName;
            }
            return null
        },//读取文件
        generateBundle(){
            this.emitFile({type: 'asset',fileName:"package.json", source:JSON.stringify(context,"","\t")})
        }
    }
}